import type { ActionType, ProColumns, FormInstance } from '@ant-design/pro-components';
import {
  PageContainer,
  ProTable,
  ProFormSelect,
  ProFormText,
  QueryFilter,
} from '@ant-design/pro-components';
import { Button, Modal, Form, Input, InputNumber, message, Avatar } from 'antd';

import React, { useRef, useState } from 'react';
import { logPage, addLog } from '@/services/back/back';

const Index: React.FC = () => {
  const [confirmRef] = Form.useForm<FormInstance<BackApi.LogAddParam>>();
  const actionRef = useRef<ActionType>();
  const queryRef = useRef<FormInstance>();
  const [extraParams, setExtraParams] = useState({
    phone: undefined,
    userName: undefined,
  });

  const fetchData = async (params: { pageSize?: number; current?: number }) => {
    const res = await logPage({
      ...params,
      pageNum: params.current,
    } as BackApi.LogQuery);
    if (res?.code !== 1000) return;
    const { list: data = [], total = 0 } = res?.data ?? {};
    return { data, success: true, total };
  };

  const fetchSearch = async (values: any) => {
    setExtraParams(values);
  };

  const handleAdd = () => {
    Modal.confirm({
      title: '新增',
      icon: null,
      content: (
        <Form form={confirmRef} autoComplete="off">
          <Form.Item label="用户ID" name="userId" rules={[{ required: true }]}>
            <Input allowClear placeholder="用户ID" />
          </Form.Item>
          <Form.Item label="次数" name="number" rules={[{ required: true }]}>
            <InputNumber placeholder="次数" style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      ),
      cancelButtonProps: {
        type: 'primary',
      },
      onCancel: () => {
        confirmRef.resetFields();
      },
      onOk: async () => {
        const pass = await confirmRef.validateFields().catch(() => false);
        if (!pass) return Promise.reject();
        const formRes: BackApi.LogAddParam = await confirmRef.getFieldsValue();
        const res = await addLog(formRes);
        if (res?.code !== 1000) return;
        message.success(res?.msg);
        confirmRef.resetFields();
        actionRef?.current?.reload?.();
        return Promise.resolve();
      },
    });
  };

  const reset = () => {
    setExtraParams({});
  };

  const columns: ProColumns<BackApi.LogItem>[] = [
    {
      title: '记录ID',
      dataIndex: 'id',
    },

    {
      title: '用户名称',
      dataIndex: 'name',
      ellipsis: true,
      render: (_, record) => record?.user?.name,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      ellipsis: true,
      render: (_, record) => record?.user?.phone,
    },
    {
      title: '头像',
      dataIndex: 'avatarUrl',
      ellipsis: true,
      render: (_, record) => <Avatar src={record?.user?.avatarUrl} />,
    },
    {
      title: '充值次数',
      dataIndex: 'number',
      ellipsis: true,
    },
    {
      title: '充值时间',
      dataIndex: 'time',
      ellipsis: true,
    },
  ];

  return (
    <PageContainer>
      {/* form */}
      <div style={{ background: '#fff', padding: 16, marginBottom: 16 }}>
        <QueryFilter
          onFinish={fetchSearch}
          onReset={reset}
          formRef={queryRef}
          defaultCollapsed={false}
        >
          <ProFormText name="userName" label="用户名" allowClear />
          <ProFormText name="phone" label="电话号码" allowClear />
        </QueryFilter>
      </div>

      {/* table */}
      <ProTable<any, any>
        headerTitle={'充值记录'}
        params={extraParams}
        request={fetchData}
        actionRef={actionRef}
        rowKey="id"
        search={false}
        columns={columns}
        toolBarRender={() => [
          <Button type="primary" key="add" onClick={handleAdd}>
            添加
          </Button>,
        ]}
      />
    </PageContainer>
  );
};

export default Index;
